package com.web;

import com.bean.Account;
import com.dao.AccountDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/phone/regist")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/account/regist.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        if (username.length() == 0 || password.length() == 0 || gender.length() == 0 || email.length() == 0 || code.length() == 0) {
            req.setAttribute("message", "字段不能为空");
            req.getRequestDispatcher("/account/registResult.jsp").forward(req, resp);
            return;
        }
        try {
            System.out.println("开始注册");
            new AccountDao().register(new Account(username, password, gender, email));
            req.setAttribute("message", "注册成功");
            req.getRequestDispatcher("/account/registResult.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "注册失败" + e.getLocalizedMessage());
            req.getRequestDispatcher("/account/registResult.jsp").forward(req, resp);
        }
    }
}
